package com.socket.batch.collector;


import com.socket.entity.GpsRecord;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.cs.ext.GBK;

import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by kaddddd on 2017/7/10 0010.
 */
public class DataAnalysis {
    private static final Logger logger = LoggerFactory.getLogger(DataAnalysis.class);
    /**
     * 解析获取的包，为后续批量写作准备
     * **/
    public static GpsRecord analysis(byte[] gpsBytes){
        GpsRecord gpsRecord = new GpsRecord();

        //String body = new String(gpsBytes);
        String body = byte2hex(gpsBytes);
        //System.out.println("body:"+body);
        //读数据
        String headFlag = body.substring(0, 2);
        //System.out.println("headFlag:"+headFlag);
        String msgLength = body.substring(2, 10);
        //System.out.println("msgLength:"+msgLength);
        String msgSn = body.substring(10, 18);
        //System.out.println("msgSn:"+msgSn);
        String msgId = body.substring(18, 22);
        //System.out.println("msgId:"+msgId);
        String msgGnsscenterid = body.substring(22, 30);
        //System.out.println("msgGnsscenterid:"+ msgGnsscenterid);
        String versionFlag = body.substring(30, 37);
        //System.out.println("versionFlag:"+ versionFlag);
        String encryptFlag = body.substring(37, 39);
        //System.out.println("encryptFlag:"+ encryptFlag);
        String encryptKey = body.substring(39, 46);
        //System.out.println("encryptKey:"+ encryptKey);
//        if(("1001").equals(msgId)){
//            System.out.println("---------------channelRead 服务端接收到登录消息了...");
//            String vehicleNo = body.substring(46, 88);
//            System.out.println("vehicleNo:"+ vehicleNo);
//            String vehicleColor = body.substring(88, 90);
//            System.out.println("vehicleColor:"+ vehicleColor);
//            String dataType = body.substring(90, 94);
//            System.out.println("dataType:"+ dataType);
//            String dataLength = body.substring(94, 102);
//            System.out.println("dataLength:"+ dataLength);
//
//        }else if(("1200").equals(msgId)) {
            System.out.println("---------------channelRead 服务端接收到GPS消息了...");
            String vehicleNo = body.substring(46, 88);
            String vehicleColor = body.substring(88, 90);
            //System.out.println("vehicleColor:"+ vehicleColor);
            String dataType = body.substring(90, 94);
            //System.out.println("dataType:"+ dataType);
            String dataLength = body.substring(94, 102);
            //System.out.println("dataLength:"+ dataLength);
            String encrypt = body.substring(102, 104);
            //System.out.println("encrypt:"+ encrypt);
            String date = body.substring(104, 112);
            String time = body.substring(112, 118);
            String lon = body.substring(118, 126);
            String lat = body.substring(126, 134);
            String vec1 = body.substring(134, 138);
            String vec2 = body.substring(138, 142);
            //System.out.println("vec2:"+ vec2);
            String vec3 = body.substring(142, 150);
            //System.out.println("vec3:"+ vec3);
            String deraction = body.substring(150, 154);
            //System.out.println("deraction:"+ deraction);
            String altitude = body.substring(154, 158);
            //System.out.println("altitude:"+ altitude);
            String state = body.substring(158, 166);
            String alarm = body.substring(166, 174);
            //System.out.println("alarm:"+ alarm);
            String crcCode = body.substring(174, 178);
            //System.out.println("crcCode:"+ crcCode);
            String endFlag = body.substring(178, 180);
            //System.out.println("endFlag:"+ endFlag);


            gpsRecord.setCreateDate(dateParser(date, time));
            //hex串转int
            int lonInt = Integer.parseUnsignedInt(lon, 16);
            double lonDouble = lonInt*1.0/1000000;
            gpsRecord.setLon(lonDouble);
            //hex串转int
            int latInt = Integer.parseUnsignedInt(lat, 16);
            double latDouble = latInt*1.0/1000000;
            //System.out.println("createDate:"+ dateParser(date, time));
            //System.out.println("lon:"+ lonDouble);
            //System.out.println("lat:"+ latDouble);
            gpsRecord.setLat(latDouble);
            String binaryState = hexString2binaryString(state);
            int online = Integer.parseInt(String.valueOf(binaryState.charAt(binaryState.length()-2)));
            gpsRecord.setOnline(online);
            //System.out.println("online:"+ online);
            int speed = Integer.parseUnsignedInt(vec1, 16);
            gpsRecord.setSpeed(speed);
            //System.out.println("speed:"+ speed);
            try {
                //System.out.println("vehicleNo:"+ new String(hex2Bytes(vehicleNo), "GBK").trim());
                gpsRecord.setVehicleNo(new String(hex2Bytes(vehicleNo), "GBK").trim());
            }catch (Exception e){
                logger.error("车牌号转化异常!");
                e.printStackTrace();
            }

            gpsRecord.setVenderType(0);
            //System.out.println(JSONObject.valueToString(gpsRecord));

//        }
        return gpsRecord;
    }

    //16进制字符串转int
    public static String dateStrParser(String dateStr){
        return String.valueOf(Integer.parseInt(dateStr.substring( 4,dateStr.length()), 16)) +"-"+Integer.parseInt(dateStr.substring(2,4), 16) +"-"+ Integer.parseInt(dateStr.substring(0,2), 16);
    }
    //16进制字符串转int
    public static String timeStrParser(String timeStr){
        int hh = Integer.parseInt(timeStr.substring(0, 2), 16);
        String hhstr = "00";
        if(hh ==0||hh ==1||hh ==2||hh ==3||hh ==4||hh ==5||hh ==6||hh ==7||hh ==8||hh ==9){
            hhstr = "0"+hh;
        }else{
            hhstr = String.valueOf(hh);
        }

        int mm = Integer.parseInt(timeStr.substring(2, 4), 16);
        String mmstr = "00";
        if(mm ==0||mm ==1||mm ==2||mm ==3||mm ==4||mm ==5||mm ==6||mm ==7||mm ==8||mm ==9){
            mmstr = "0"+mm;
        }else{
            mmstr = String.valueOf(mm);
        }
        return hhstr +":"+ mmstr +":"+
                String.valueOf(Integer.parseInt(timeStr.substring(4, timeStr.length()), 16));
    }

    public static Date dateParser(String dateStr, String timeStr){
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        Date date = null;
        String dateAndTime = dateStrParser(dateStr) + " " + timeStrParser(timeStr);
        try {
            date = sdf.parse(dateAndTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static byte[] hex2Bytes1(String src){
        byte[] res = new byte[src.length()/2];
        char[] chs = src.toCharArray();
        int[] b = new int[2];

        for(int i=0,c=0; i<chs.length; i+=2,c++){
            for(int j=0; j<2; j++){
                if(chs[i+j]>='0' && chs[i+j]<='9'){
                    b[j] = (chs[i+j]-'0');
                }else if(chs[i+j]>='A' && chs[i+j]<='F'){
                    b[j] = (chs[i+j]-'A'+10);
                }else if(chs[i+j]>='a' && chs[i+j]<='f'){
                    b[j] = (chs[i+j]-'a'+10);
                }
            }

            b[0] = (b[0]&0x0f)<<4;
            b[1] = (b[1]&0x0f);
            res[c] = (byte) (b[0] | b[1]);
        }

        return res;
    }

    public static byte[] hex2Bytes(String src){
        byte[] res = new byte[src.length()/2];
        char[] chs = src.toCharArray();
        for(int i=0,c=0; i<chs.length; i+=2,c++){
            try {
                res[c] = (byte) (Integer.parseInt(new String(chs, i, 2), 16));
            }catch(Exception e){
                System.out.println("i:"+i);
                System.out.println("chs:"+chs);
                System.out.println("c:"+c);
                System.out.println("res[c]:"+res[c]);
            }
        }

        return res;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    public static void main(String[] args)
    {
        String hexString = "0F112E";
        System.out.println(timeStrParser(hexString));
    }

    public static String hexString2binaryString(String hexString)
    {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++)
        {
            tmp = "0000"
                    + Integer.toBinaryString(Integer.parseInt(hexString
                    .substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }
}
